package com.lyubia.shop.rpc.service.impl;

import com.lyubia.shop.common.result.ShopPageInfo;
import com.lyubia.shop.api.service.SearchService;
import com.lyubia.shop.api.vo.GoodsVo;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0", interfaceClass = SearchService.class)
public class SearchServiceImpl implements SearchService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public ShopPageInfo<GoodsVo> doSearch(String searchStr, Integer pageNum, Integer pageSize) {
        ShopPageInfo<GoodsVo> pageInfo = null;
        try {
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

            NativeSearchQuery query = nativeSearchQueryBuilder
                    .withQuery(QueryBuilders.multiMatchQuery(searchStr, "goodsName"))
                    .withPageable(PageRequest.of(pageNum-1, pageSize))
                    .withHighlightBuilder(new HighlightBuilder()
                            .field("goodsName")
                            .preTags("<span style='color:red;'>")
                            .postTags("</span>"))
                    .build();
            SearchHits<GoodsVo> search = elasticsearchRestTemplate.search(query, GoodsVo.class);

            List<GoodsVo> goodsVoList = new ArrayList<>();
            for (SearchHit<GoodsVo> searchHit : search) {
                GoodsVo goodsVo = searchHit.getContent();
                goodsVo.setGoodsNameHl(searchHit.getHighlightField("goodsName").get(0));
                goodsVoList.add(goodsVo);
            }
            pageInfo = new ShopPageInfo<>(pageNum, pageSize, new Long(search.getTotalHits()).intValue());
            pageInfo.setResult(goodsVoList);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
